package com.id.coinscleaner.utils

import android.telephony.TelephonyManager
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.id.coinscleaner.App.Companion.appContext

object Country {
    private val DefaultCountry = arrayOf("tw", "jp", "kr", "br", "qa", "ua", "co", "id", "hk", "fr", "it", "ro", "tr","en")

    fun manualConfig(vararg country: String): Boolean = therein(*country)

    fun remoteConfig(vararg defaultCountryConfig: String = DefaultCountry): Boolean {
        val country = Firebase.remoteConfig.getString("country").let { if (it.isEmpty()) defaultCountryConfig else it.formatJson() }
        return manualConfig(*country)
    }

    private fun therein(vararg country: String): Boolean {
        val telephonyManager = appContext.getSystemService(AppCompatActivity.TELEPHONY_SERVICE) as TelephonyManager
        val countryIso = telephonyManager.networkCountryIso
        Log.w(javaClass.name, "Country.therein -> $countryIso")
        try {
            Events.sendEvent("country", mapOf("iso" to countryIso, "countrys" to country.toJson()))
        } catch (e: Throwable) {
        }
        if (countryIso.isNullOrEmpty()) return false
        for (item in country) {
            if (countryIso.contentEquals(item, true)) return true
        }
        return false
    }
}

fun Any.toJson(): String = Gson().toJson(this)

inline fun <reified T> String.formatJson(): T {
    if (T::class.java == String::class.java) return this as T
    val typeToken = object : TypeToken<T>() {}.type
    return Gson().fromJson(this, typeToken)
}